package com.wang.vedio;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.tools.ScreenUtils;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogLoading;
import com.vondear.rxui.view.dialog.RxGuangGaoDialog;
import com.wang.vedio.application.APP;
import com.wang.vedio.bean.BannerBean;
import com.wang.vedio.broadcast.ScreenStatusReceiver;
import com.wang.vedio.fragment.GameFragment;
import com.wang.vedio.fragment.MainFragment;
import com.wang.vedio.fragment.PersonalCenterFragment;
import com.wang.vedio.fragment.SearchFragment;
import com.wang.vedio.net.SharedHelper;
import com.wang.vedio.net.entity.BaseBean;
import com.wang.vedio.net.rxjava.HttpMethods;
import com.wang.vedio.net.subscribers.ProgressSubscriber;
import com.wang.vedio.net.subscribers.SubscriberOnNextListener;
import com.wang.vedio.permission.MPermission;
import com.wang.vedio.permission.annotation.OnMPermissionDenied;
import com.wang.vedio.permission.annotation.OnMPermissionGranted;
import com.wang.vedio.permission.annotation.OnMPermissionNeverAskAgain;
import com.wang.vedio.utils.NotificationUtil;
import com.wang.vedio.utils.statusbar.StatusBarUtil;
import com.wang.vedio.widget.FragmentAda;
import com.wang.vedio.widget.MyViewPager;
import com.wang.vedio.widget.TabPageIndicator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class MainActivity extends AppCompatActivity {
    private void requestBasicPermission() {
        MPermission.with(MainActivity.this).setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS).request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {

    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        RxToast.normal("部分权限开启失败，可能会影响操作");
    }

    /**
     * 基本权限管理
     */
    private final int BASIC_PERMISSION_REQUEST_CODE = 110;
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    @BindView(R.id.main_viewpager)
    MyViewPager mViewPager;
    @BindView(R.id.tab)
    TabPageIndicator tabPageIndicator;

    private String[] titles = {"推荐", "找片", "游戏", "任务"};
    private int[] selectTabIcon = {R.mipmap.gyss_tab1_select,
            R.mipmap.gyss_tab2_select, R.mipmap.gyss_tab3_select,
            R.mipmap.gyss_tab4_select};
    private int[] unSelectTabIcon = {R.mipmap.gyss_tab1_normal,
            R.mipmap.gyss_tab2_normal, R.mipmap.gyss_tab3_normal,
            R.mipmap.gyss_tab4_normal};
    private ArrayList<Fragment> fragList = new ArrayList<Fragment>();
    //退出时的时间
    private long mExitTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_layout1);
        APP.getInstance().add(this);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBar(this, true, R.color.transparent, false, false);
        initFragments();
        initViewPager();
        initView();

        getTanChu();

        registSreenStatusReceiver();
    }

    private ScreenStatusReceiver mScreenStatusReceiver;
    private void registSreenStatusReceiver() {
        mScreenStatusReceiver = new ScreenStatusReceiver();
        IntentFilter screenStatusIF = new IntentFilter();
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mScreenStatusReceiver, screenStatusIF);
    }

    private RxDialogLoading loadDialog;
    public void showLoadingDialog(){
        if(loadDialog == null){
            loadDialog = new RxDialogLoading(this);
        }
        loadDialog.show();
    }

    public void hideLoadDialog(){
        if(loadDialog != null){
            loadDialog.dismiss();
        }
    }

    private void getTanChu(){
        showLoadingDialog();
        SubscriberOnNextListener<BaseBean<List<BannerBean>>> onNextListener = baseBean -> {
            hideLoadDialog();
            if(baseBean.getData() != null && baseBean.getData().size() > 0){
                //弹出广告
                showGuangGaoDialog(baseBean.getData().get(0).getAdImg(),baseBean.getData().get(0).getAdPath());
            }
        };
        Map<String, Object> params = new HashMap<>();
        params.put("adCode", "dayTanChuAdCode");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getBannerByCode(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    private boolean canSign = false;
    private void isNeedSign(){
        showLoadingDialog();
        SubscriberOnNextListener<BaseBean<Boolean>> onNextListener = baseBean -> {
            hideLoadDialog();
            canSign = baseBean.getData();
//            if(fragList.get(0) != null){
//                ((MainFragment)fragList.get(0)).setCouldClick(canSign);
//            }
//            if(fragList.get(1) != null){
//                ((SearchFragment)fragList.get(1)).setCouldClick(canSign);
//            }
//            if(fragList.get(2) != null){
//                ((GameFragment)fragList.get(2)).setCouldClick(canSign);
//            }
//            if(fragList.get(3) != null){
//                ((PersonalCenterFragment)fragList.get(3)).setCouldClick(canSign);
//            }
        };
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(this));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().isNeedSign(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }

    private void showGuangGaoDialog(String adImg,String adPath){
        RxGuangGaoDialog dialog = new RxGuangGaoDialog(this);
        dialog.getBtn_close().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.getAdImg().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到广告
            }
        });
        Glide.with(dialog.getAdImg())
                .load(HttpMethods.BASE_URL+adImg)
                .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(10))))
                .into(dialog.getAdImg());
        dialog.show();
    }


    public boolean isCanSign(){
        return canSign;
    }

    //对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出到后台
     */
    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次进入后台", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        fragList.get(mViewPager.getCurrentItem()).onActivityResult(10,RESULT_OK,data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initFragments() {
        MainFragment bmfwFrag = new MainFragment();
        fragList.add(bmfwFrag);
        SearchFragment fxxsFragment = new SearchFragment();
        fragList.add(fxxsFragment);
        GameFragment dcqzFragment = new GameFragment();
        fragList.add(dcqzFragment);
        PersonalCenterFragment personalCenterFragment = new PersonalCenterFragment();
        fragList.add(personalCenterFragment);
    }

    private void initViewPager() {
        mViewPager.setStatic(true);
        mViewPager.setAdapter(new FragmentAda(getSupportFragmentManager(), fragList,null));
        tabPageIndicator.setTitles(titles).setNormalTextSize(12)
                .setSelectBgIcon(-1).setUnSelectBgIcon(-1)
                .setSelectTextColor(R.color.tab_menu_text_select)
                .setUnSelectTextColor(R.color.tab_menu_text_normal)
                .setSelectTabIcon(selectTabIcon)
                .setUnSelectTabIcon(unSelectTabIcon)
                .setTabWidth(ScreenUtils.getScreenWidth(this) / titles.length)
                .setTabHeight(ScreenUtils.dip2px(this, 60))
                .setViewPager(mViewPager);
        tabPageIndicator.setOnTabClickListener(new TabPageIndicator.TabClickListener() {
            @Override
            public void onTabClick(String tabTitle) {

            }
        });
        mViewPager.setCurrentItem(0);
    }


    private void initView() {
        requestBasicPermission();
        //通知权限判断
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //判断是否需要开启通知栏功能
            NotificationUtil.OpenNotificationSetting(this, new NotificationUtil.OnNextLitener() {
                @Override
                public void onNext(int type) {
                    //获取版本信息

                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mScreenStatusReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isNeedSign();
    }
}
